<?php

declare(strict_types=1);

namespace app\yperp\common;

use DateTime;
use GuzzleHttp\Psr7\Request;
use GuzzleHttp\Psr7\Utils;
use GuzzleHttp\Client;

trait SuosiHttp
{
    function require($url = '', $body = [], $method = 'POST', $headers = [])
    {
        $client = new Client(['verify' => env('root_path') . 'application\yperp\common\cacert.pem',]);

        $headers['authorization'] = $this->token;
        $headers['content-type'] = 'application/json;charset=utf-8';
        // dump($headers);
        $body = json_encode($body, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
        dump($body);
        $request = new Request($method, $url, $headers, $body);
        $res = $client->sendAsync($request)->wait();
        $res = $res->getBody()->getContents();
        return json_decode($res, true);
    }
    /**
     * 搜索获取一个员工二维码
     */
    function search_staff_qr_one($keyword, $presion_grpup_id)
    {
        $url = 'https://m.suosishequ.com/gateway/group/web/liveCode/staff/page';
        $response = $this->require($url, [
            "groupId" => $presion_grpup_id,
            // "search" => (object) [],
            "search" => (object) ['keyword' => $keyword],
            "pageNo" => 1,
            "pageSize" => 1,
        ]);
        return $response['data']['dataSource'];
    }

    function get_staff_qr_list($group_id)
    {
        $url = 'https://m.suosishequ.com/gateway/group/web/liveCode/staff/page';
        $response = $this->require($url, [
            "groupId" => $group_id,
            "search" => (object) [],
            // "search" => (object) ['keyword' => "杨利娟"],
            "pageNo" => 1,
            "pageSize" => 300,
        ]);
        return $response['data']['dataSource'];
    }
    public function method_user_search_all($keyword = '李世平', $check_dept = [])
    {
        $url = 'https://m.suosishequ.com/gateway/user-center/select/component/search';
        $params = ['keyword' => $keyword, 'types' => ['innerContacts'], 'selectTypeList' => ['user_and_dept']];
        $data = $this->require($url, $params);
       
        $response_data = [];
        if (count($data['data']['dataSource']) > 0) {
            $data = $data['data']['dataSource'];
            foreach ($data as $values) {
                $item = [
                    'id' => $values['key'],
                    'name' => $values['label'],
                    'type' => $values['type'],
                ];
                if ($check_dept !== []) {
                    if (isset($check_dept['id']) && in_array($item['id'], $check_dept['id'])) {
                        $response_data[] = $item;
                    } else if (isset($check_dept['name']) && in_array($item['name'], $check_dept['name'])) {
                        $response_data[] = $item;
                    } else if (isset($check_dept['key']) && in_array($item['key'], $check_dept['key'])) {
                        $response_data[] = $item;
                    }
                } else {
                    $response_data[] = $item;
                }

            }
        }
        return $response_data;


    }
    public function method_user_search($keyword = '李世平', $check_dept = '')
    {
        $url = 'https://m.suosishequ.com/gateway/user-center/select/component/search';
        $params = ['keyword' => $keyword, 'types' => ['innerContacts'], 'selectTypeList' => ['user_and_dept']];
        $data = $this->require($url, $params);
        $response = [];
        $response_data = [];
        if (count($data['data']['dataSource']) > 0) {
            $data = $data['data']['dataSource'];
            foreach ($data as $key => $values) {
                foreach ($values['userDeptList'] as $k => $item) {
                    // dump([$item['deptName'], $check_dept]);
                    if ($this->similar($item['deptName'], $check_dept) > 50) {

                        $response_data = $values;
                    }
                }
            }
        }
        if (!empty($response_data)) {
            $response = [
                "id" => $response_data['key'],
                "key" => $response_data['key'],
                "name" => $response_data['label'],
                "type" => "USER",
                "orgId" => 100010,
                "contactType" => 1,
                "childDelete" => true
            ];
        }

        return $response;


    }

    public function method_tag_search($keyword = '杜明虹', $check_dept = '分部客户资产')
    {
        $url = 'https://m.suosishequ.com/gateway/user-center/select/component/search';
        $param = ['keyword' => $keyword, 'types' => ['customerTagContacts'], 'selectTypeList' => ['tag']];
        $response = $this->require($url, $param);
        dump(['method_tag_search $response' => $response]);
        $response_data = [];
        if (count($response['data']['dataSource']) > 0) {

            $dataSource = $response['data']['dataSource'];
            $dataSource_find = [];
            foreach ($dataSource as $key => $value) {
                if ($value['labelPathName'] !== $check_dept) {
                    continue;
                }
                if ($value['label'] == $keyword) {
                    $dataSource_find = $value;
                }
            }
            if (!empty($dataSource_find)) {
                $response_data = [
                    'id' => $dataSource_find['key'],
                    'key' => $dataSource_find['key'],
                    'name' => $dataSource_find['label'],
                    'type' => 'CUSTOMER_TAG',
                    'orgId' => '100010',
                    'contactType' => 9,
                    'childDelete' => true
                ];
            }

        }
        return $response_data;

    }



    public function method_tag_create($customerTagInfoList = [], $check_dept = '')
    {
        $url = 'https://m.suosishequ.com/gateway/user-center/select/component/result';
        $data = [
            'selectTypeList' => ['tag'],
            'tagTypeList' => [1],
            'labelPermission' => 1,
            'deptInfoList' => [],
            'userInfoList' => [],
            'groupInfoList' => [],
            'tagInfoList' => [],
            'customerTagInfoList' => $customerTagInfoList,
            'types' => ['customerTagContacts'],
            'weChatTagInfoList' => [],
            'customerManagerInfoList' => [],
            'managerUserInfoList' => [],
            'managerGroupInfoList' => [],
            'employeeCodeInfoList' => [],
            'groupTagInfoList' => [],
            'circlesTagInfoList' => [],
            'contentTagInfoList' => [],
            'equipmentInfoList' => [],
            'tvInfoList' => [],
            'maternalInfoList' => [],
            'cameraInfoList' => [],
            'workGroupInfoList' => [],
            'id' => '100010-' . $this->create_time_str(),
        ];

        // dump($data);
        $data = $this->require($url, $data);
        return $data;

    }



    function save_preson_qr($params = [])
    {
        $url = 'https://m.suosishequ.com/gateway/group/web/liveCode/staff/save';

        // $userDeptList = $this->method_user_search('李世平', $params['check_dept']);
        $labelSignature = $this->method_tag_create([
            $this->method_tag_search($params['shopname']),//'广元美天美电器有限公司'
            $this->method_tag_search($params['name']),//杜明虹
            $this->method_tag_search($params['dept_type']), //绵阳冰洗中心
        ]);

        $param = [
            'name' => $params['name'],
            'groupId' => $params['groupId'],
            'statFlagIdList' => [],
            'skipVerify' => 0,
            'userDeptList' => [
                [
                    "id" => "1760928920526579225",//李世平-机器人  1760928920526580113   //李世平-真机 1760928920526579225
                    "name" => "李世平",
                    "type" => "USER"
                ]
            ],
            'labelSignature' => $labelSignature['data'],
            'hskBean' => ['welcomeType' => 1],
        ];
        dump(['save_preson_qr' => $param]);
        // return $param;
        $response = $this->require($url, $param);
        return $response;
    }

    /**
     * 获取个人活码详情
     * @param mixed $id
     * @return mixed
     */
    function getUserQRUpdateDetail($id)
    {
        $url = 'https://m.suosishequ.com/gateway/group/web/liveCode/staff/getUpdateDetail?id=' . $id;
        $response = $this->require($url, [], 'GET');
        dump(['getUserQRUpdateDetail' => $response]);
        return $response['data'];
    }
    function update_preson_qr_by_param($params = [])
    {
        $url = 'https://m.suosishequ.com/gateway/group/web/liveCode/staff/update';
        $response = $this->require($url, $params);
        return $response;
    }
    /**
     * 获取员工二维码列表
     */
    function get_staff_qr_list_by_yieid($keyword = '', $presion_grpup_id = "1")
    {

        $url = 'https://m.suosishequ.com/gateway/group/web/liveCode/staff/page';
        $isTrue = true;
        $dataNumber = 1;
        while ($isTrue) {
            $param = [
                "groupId" => (string) $presion_grpup_id,
                // "search" => (object) [],
                // "search" => (object) ['keyword' => $keyword],
                "pageNo" => $dataNumber,
                "pageSize" => 1,
            ];
            if ($keyword === '') {
                $param['search'] = (object) [];
            } else {
                $param['search'] = (object) ['keyword' => $keyword];
            }

            $response = $this->require($url, $param);
            dump(['$dataNumber' => $dataNumber, '$param' => $param, '$response' => $response]);
            yield $response['data']['dataSource'];
            $dataNumber = $response['data']['pagination']['current'] * $response['data']['pagination']['pageSize'];
            if ($dataNumber > $response['data']['pagination']['total']) {
                $isTrue = false;
            }
            $dataNumber++;
        }


    }
    function update_preson_qr($params = [])
    {
        $url = 'https://m.suosishequ.com/gateway/group/web/liveCode/staff/update';

        // $userDeptList = $this->method_user_search('李世平', $params['check_dept']);
        $tags = [
            $this->method_tag_search($params['shopname']),//'广元美天美电器有限公司'
            $this->method_tag_search($params['name']),//杜明虹
            $this->method_tag_search($params['dept_type']), //绵阳冰洗中心
        ];
        foreach ($tags as $key => $tag) {
            if (empty($tag)) {
                unset($tags[$key]);
            }
        }
        dump(['$tags' => $tags]);
        $labelSignature = $this->method_tag_create($tags);
        $hskIdList = $this->search_msg_tmpl_ids($params['shopname']);
        $param = [
            'id' => $params['id'],
            // 'name' => $params['name'],preson_qr_name
            'name' => $params['preson_qr_name'],
            'groupId' => $params['groupId'],
            'statFlagIdList' => [],
            'skipVerify' => 0,
            'userDeptList' => [
                [
                    "id" => "1760928920526579225",
                    "name" => "李世平",
                    "type" => "USER"
                ]
            ],
            'labelSignature' => $labelSignature['data'],
            'hskBean' => [
                'welcomeType' => 1,
                "welcomeContent" => "[curreceiver] 宝贝你终于来啦！以后我就是你的家电顾问啦！以后输入数字0，就可以接入我们在线客服啦！ 长按扫码加入下方门店群每周都有福利等你哦！虹包雨、家电使用技巧等不要错过哦!",
                "hskIdList" => [
                    $hskIdList
                ]
            ],
            'remark' => '',

        ];
        dump(['update_preson_qr' => $param]);
        // return $param;
        $response = $this->require($url, $param);
        return $response;
    }
    function search_msg_tmpl_ids($keyword)
    {
        $url = 'https://m.suosishequ.com/gateway/hsk/web/hs/page';
        $param = [
            "appCode" => "hsk",
            "search" => ["keyword" => $keyword, "newsTypes" => "3"],
            "newsTypes" => ["3"],
            "pageNo" => 1,
            "pageSize" => 20
        ];
        dump(['search_msg_tmpl_ids_$param' => $param]);
        $response = $this->require($url, $param);
        return $response['data']['dataSource'][0]['id'];
    }


    public function search_group($keyword, $check_dept = '')
    {
        $check_dept = $check_dept !== '' ? $check_dept : $keyword;
        // $check_dept = '测试区群';
        // $keyword= '测试区群';
        dump([$keyword, $check_dept]);
        $url = 'https://m.suosishequ.com/gateway/user-center/select/component/search';
        $param = [
            "keyword" => $keyword,

            "types" => [
                "groupContacts"
            ],
            "selectTypeList" => [
                "user",
                "member",
                "group"
            ]
        ];
        $response = $this->require($url, $param);
        dump(['搜索群名称' => $response]);
        $dataSource = $response['data']['dataSource'];
        $dataSource_find = [];

        foreach ($dataSource as $key => $value) {
            // dump([$value['extendedAttribute']['groupName'], $check_dept]);
            if ($value['extendedAttribute']['groupName'] == $check_dept) {
                $dataSource_find = $value;
            }
        }

        $response_data = [];
        if (!empty($dataSource_find)) {
            $response_data = [
                "id" => $dataSource_find['key'],
                "key" => $dataSource_find['key'],
                "name" => $dataSource_find['label'],
                "type" => "GROUP",
                "contactType" => 3,
                "extendedAttribute" => [
                    'wxUserId' => $dataSource_find['extendedAttribute']['wxUserId'],
                    // 'groupName' => $dataSource_find['groupName'],
                    'chatId' => $dataSource_find['extendedAttribute']['chatId'],
                    'totalMember' => $dataSource_find['extendedAttribute']['totalMember'],
                    'userName' => $dataSource_find['extendedAttribute']['userName'],
                    'userId' => $dataSource_find['extendedAttribute']['userId'],
                ],
                "childDelete" => true
            ];
        }
        return $response_data;
    }

    /**
     * 创建群二维码和群标签
     */
    public function create_group_qr($params)
    {
        $tags = [];
        $shopname = $this->method_tag_search($params['shopname']);//'广元美天美电器有限公司'
        if (!empty($shopname)) {
            $tags[] = $shopname;
        }
        // $name = $this->method_tag_search($params['name']);//杜明虹
        // if (!empty($name)) {
        //     $tags[] = $name;
        // }
        // $dept_type = $this->method_tag_search($params['dept_type']); //绵阳冰洗中心
        // if (!empty($dept_type)) {
        //     $tags[] = $dept_type;
        // }

        $url = 'https://m.suosishequ.com/gateway/group/web/liveCode/group/save';
        $param = [
            "name" => $params['groupName'],
            "groupId" => $params['dep'],
            "groupSignature" => [$this->search_group($params['BaseName'])],
            "labelSignature" => $this->method_tag_create($tags)['data'],
            "autoCreateRoom" => 1,
            "roomBaseName" => $params['BaseName'], //我是群名称前缀
            "roomBaseId" => 1
        ];

        dump($param);
        $data = $this->require($url, $param);

        return $data;
    }
    public function update_group_qr($params)
    {
        $tags = [];
        $shopname = $this->method_tag_search($params['shopname']);//'广元美天美电器有限公司'
        if (!empty($shopname)) {
            $tags[] = $shopname;
        }
        // $name = $this->method_tag_search($params['name']);//杜明虹
        // if (!empty($name)) {
        //     $tags[] = $name;
        // }
        $dept_type = $this->method_tag_search($params['dept_type']); //绵阳冰洗中心
        if (!empty($dept_type)) {
            $tags[] = $dept_type;
        }
        $url = 'https://m.suosishequ.com/gateway/group/web/liveCode/group/update';

        $param = [
            "id" => $params['id'],
            "name" => $params['groupName'],
            "groupId" => $params['dep'],
            "groupSignature" => [$this->search_group($params['BaseName'])],
            "labelSignature" => $this->method_tag_create($tags)['data'],
            "autoCreateRoom" => 1,
            "roomBaseName" => $params['BaseName'], //我是群名称前缀
            "roomBaseId" => 1,
            "groupLabelSignature" => "",
        ];
        dump($param);
        $data = $this->require($url, $param);

        return $data;
    }

    //获取所有群活码列表
    public function search_group_qr_one($keyword = '')
    {
        $url = 'https://m.suosishequ.com/gateway/group/web/liveCode/group/findPageList';
        $response = $this->require($url, [
            "groupId" => "1",
            // "search" => (object) [],
            "search" => (object) ['keyword' => $keyword],
            "pageNo" => 1,
            "pageSize" => 1
        ]);
        // dump($response);
        return $response['data']['dataSource'];

    }
    //获取所有群活码列表
    public function get_group_qr_list($groupid = '')
    {
        $url = 'https://m.suosishequ.com/gateway/group/web/liveCode/group/findPageList';
        $response = $this->require($url, [
            "groupId" => (string) $groupid,
            "search" => (object) [],
            // "search" => (object) ['keyword' => "成都营门口店"],
            "pageNo" => 1,
            "pageSize" => 300
        ]);
        // dump($response);
        return $response['data']['dataSource'];

    }

    public function upload_img($image_url = '')
    {
        $client = new Client(['verify' => env('root_path') . 'application\yperp\common\cacert.pem',]);

        $image_url_array = explode('/', $image_url);
        $filename = (string) end($image_url_array);
        $url = 'https://m.suosishequ.com/gateway/file-center/web/file/uploadFileList?isSyncZip=1&urlZipLimit=1024&appCode=hsk&groupId=0&bizGroupId=0';

        $headers = [
            'authorization' => $this->token,
        ];
        $options = [
            'multipart' => [
                [
                    'name' => 'file',
                    'contents' => Utils::tryFopen($image_url, 'r'),
                    'filename' => $filename,
                ]
            ]
        ];
        $request = new Request('POST', $url, $headers);
        $res = $client->sendAsync($request, $options)->wait();
        $res = $res->getBody()->getContents();
        return json_decode($res, true);
    }

    public function add_message_img_tmpl($param)
    {
        $url = 'https://m.suosishequ.com/gateway/cms/web/news/level/add';
        $response = $this->require($url, [
            "title" => $param['title'],
            "coverUrl" => $param['coverUrl'],
            "qrCode" => [
                "qrSwitch" => false,
                "location" => []
            ],
            "columnIds" => [
                $param['columnIds']
            ],
            "qrSwitch" => 0,
            "location" => "{}",
            "appCode" => "hsk",
            "newsType" => 3
        ], 'POST', [
            'app-code' => 'notice-simple'
        ]);
        return $response;
    }
    public function update_group_tag($params)
    {
        $url = 'https://m.suosishequ.com/gateway/group/pc/internalGroupManager/updateLabel';
        $response = $this->require($url, $params);
        dump(['update_group_tag' => $response]);
    }

    public function get_group_list()
    {    //获取群活码列表
        $url = 'https://m.suosishequ.com/gateway/group/web/liveCode/group/findPageList';
        $response = $this->require($url, [
            "groupId" => '1',
            "search" => (object) [],
            // "search" => (object) ['keyword' => "四川星普五星电器德阳店"],
            "pageNo" => 1,
            "pageSize" => 500
        ]);
        dump($response);
        return $response['data']['dataSource'];
    }

    public function search_group_tag($tag_name)
    {
        $url = 'https://m.suosishequ.com/gateway/user-center/select/component/search';
        $response = $this->require($url, [
            "keyword" => $tag_name,
            "types" => ["groupTagContacts"],
            "selectTypeList" => ["tag"],
            "noTagLabelPermission" => false,
            "tagTypeList" => [1]
        ]);
        dump(['search_group_tag' => $response]);
        // return $response['data']['dataSource'][0];
        if (!count($response['data']['dataSource'])) {
            return [];
        } else {

            return [
                "id" => $response['data']['dataSource'][0]['key'],
                "name" => $response['data']['dataSource'][0]['label'],
                "childDelete" => true,
                "labelPathName" => "分部",
                "type" => "GROUP_TAG",
                "key" => $response['data']['dataSource'][0]['key'],
                "orgId" => 100010,
                "contactType" => 14,
            ];
        }

    }
    public function search_group_name($group_name)
    {
        $url = 'https://m.suosishequ.com/gateway/group/pc/internalGroupManager/findPageList';
        $response = $this->require($url, [
            "search" => ["groupName" => "$group_name"],
            "pageNo" => 1,
            "pageSize" => 1,
        ]);
        dump(['search_group_name' => $response]);
        if (isset($response['data']['dataSource'][0])) {
            return $response['data']['dataSource'][0];
        }
        return false;
    }

    public function get_now_group_detail($group_id)
    {
        $url = 'https://m.suosishequ.com/gateway/group/pc/internalGroupManager/detail';
        $response = $this->require($url, [
            "id" => $group_id
        ], 'GET');

        dump(['get_now_group_detail' => $response]);
        return isset($response['data']['formValue']['groupLabelSignature']) ? true : false;
    }


    function create_time_str()
    {

        // 获取当前时间
        $date = new DateTime();
        $microseconds = sprintf("%06d", ($date->format("u")));

        // 格式化时间值
        $time_value = $date->format("YmdHis") . $microseconds;

        return $time_value;

    }


    function similar($string1, $string2)
    {
        similar_text($string1, $string2, $percent);
        return (int) $percent;
    }
}
